package org.springframework.zp.batis.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.BeanDefinitionHolder;
import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import java.util.HashMap;
import java.util.Map;
import java.util.Set;

@Slf4j(topic = "e")
public class MyImportBeanDefinitionRegistart implements ImportBeanDefinitionRegistrar {
	Map<String,BeanDefinition> map= new HashMap<>();

	Set<BeanDefinitionHolder> beanDefinitionHolders = null;

	public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry){
		//完成了扫描 --put bdmap会多两个 BeanDefinition
		Map<String, Object> annotationAttributes = importingClassMetadata.getAnnotationAttributes(MyScan.class.getName());

		// 扫包
		scan(registry,annotationAttributes);

		// 针对 BeanDefinition 进行处理，实现替换代理类
		for (BeanDefinitionHolder beanDefinitionHolder : beanDefinitionHolders) {
			AbstractBeanDefinition mapperBd = (AbstractBeanDefinition) beanDefinitionHolder.getBeanDefinition();
			String beanClassName = mapperBd.getBeanClassName();

			// 调用自己 MyFactoryBean 创建代理类
			mapperBd.setBeanClass(MyFactoryBean.class);
			mapperBd.getPropertyValues().add("mapperInterface",beanClassName);
		}
	}

	/**
	 * 根据注解里面的配置的包路径进行扫包
	 *
	 * @param registry
	 * @param annotationAttributes
	 */
	public void scan(BeanDefinitionRegistry registry,Map<String, Object> annotationAttributes){
		String scanPackageName = (String) annotationAttributes.get("value");

		// 调用自定义的扫包代码
		MyMapperScaner scaner = new MyMapperScaner(registry,true);
		beanDefinitionHolders = scaner.doScan(scanPackageName);

//		BeanDefinitionBuilder builder = BeanDefinitionBuilder.genericBeanDefinition(TMapper.class);
//		map.put("tmapper",builder.getBeanDefinition());
//		builder = BeanDefinitionBuilder.genericBeanDefinition(AMapper.class);
//		map.put("amapper",builder.getBeanDefinition());
	}


}
